import os, sys
import base64
import logging
import io
from flask import Flask, send_file, make_response, render_template
# from flask_limiter import Limiter
# from flask_limiter.util import get_remote_address

from pywebio.platform.flask import webio_view
from manage import PYWEB
from settings import LINKIMAGE, PORT

logging.basicConfig(level=20, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', \
    datefmt='%a, %d %b %Y %H:%M:%S', filename='./info.log', filemode='a+')

PYWEB_INSTANCE = PYWEB()

app = Flask(__name__)

app.add_url_rule('/manage', 'webio_view', webio_view(PYWEB.task_func),
            methods=['GET', 'POST', 'OPTIONS'])


# limiter = Limiter(
#     app,
#     key_func=get_remote_address,                       #根据访问者的IP记录访问次数
#     default_limits=["10000 per day", "1000 per hour"]  #默认限制，一天最多访问200次，一小时最多访问50次
# )


@app.route('/files/<file_html>', methods=['GET', 'POST'])
#@limiter.limit("20/second", override_defaults=False)
def post_file(file_html):
    if len(file_html) >= 6 and file_html[-5:] == ".html":
        #html = "./templates/" + file_html
        return render_template(file_html)
    else:
        return "输入错误，请重试"

@app.route('/image/<image_name>', methods=['GET', 'POST'])
#@limiter.limit("20/second", override_defaults=False)
def post_image(image_name):
    try:
        if ".png" in image_name:
            with open("./image/"+image_name, "rb") as f:
                res = base64.b64encode(f.read())
            #     return res

            return send_file(
                    io.BytesIO(res),
                    mimetype='image/png',
                    as_attachment=True,
                    attachment_filename="./image/"+image_name
                )
        else:
            "无此文件"
    except:
        return "无此文件"

def init():
    if not os.path.exists("data"):
        os.mkdir("data")
    if not os.path.exists("image"):
        os.mkdir("image")
    if not os.path.exists("templates"):
        os.mkdir("templates")
    if not os.path.exists("files"):
        os.mkdir("files")

if __name__ == '__main__':

    init()

    app.run(host='0.0.0.0', port=PORT)
